<template>
  <div>
    <el-table
      v-loading="listloading"
      :data="kindListData.items"
      class="fb-table no-table-hover"
      element-loading-text="加载中..."
      empty-text="暂无数据"
      fit
      hightlight-current-row>
      <el-table-column v-if="type" align="left" min-width="140px" label="预警类型">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.module | formatModuleName" />
        </template>
      </el-table-column>
      <el-table-column v-if="type" align="left" min-width="140px" label="通知条件">
        <template slot-scope="scope">
          <ToolTip :content="formatCondition(scope.row.condition)" />
        </template>
      </el-table-column>
      <el-table-column v-if="!type" align="left" min-width="140px" label="通知类型">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.moduleName" />
        </template>
      </el-table-column>
      <el-table-column v-if="!type" align="left" min-width="140px" label="通知对象">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.receiveName" />
        </template>
      </el-table-column>
      <el-table-column v-if="!type" align="left" min-width="80px" label="通知范围">
        <template slot-scope="scope">
          {{ scope.row.type | typeFilter }}
        </template>
      </el-table-column>
      <el-table-column align="left" min-width="80px" label="通知周期">
        <template slot-scope="scope">
          {{ scope.row.cycle | cycleFilter }}
        </template>
      </el-table-column>
      <el-table-column align="left" min-width="150px" label="通知时间">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.cycleName" />
        </template>
      </el-table-column>
      <el-table-column v-if="type" align="left" min-width="140px" label="通知内容">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.notifyContent" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="创建人">
        <template slot-scope="scope">
          <ToolTip :content="type?scope.row.creator:scope.row.createrName" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="创建时间" min-width="180px">
        <template slot-scope="scope">
          <span v-if="scope.row.createTime">{{ scope.row.createTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column :fixed="showMobilePage?false:'right'" :width="type?150:100" align="left" label="操作">
        <template slot-scope="scope">
          <el-button type="text" class="btn-right" @click="handleEdit(scope.row)"><span style="font-size:14px;">编辑</span></el-button>
          <el-button v-if="type" class="btn-right" type="text" @click="handleCopy(scope.row)"><span style="font-size:14px;">复制</span></el-button>
          <el-button type="text" @click="deleteItem(scope.row)"><span style="font-size:14px;">删除</span></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="display:flex;justify-content:flex-end;margin-top:8px;">
      <el-pagination
        :current-page="page"
        :page-size="perPage"
        :total="kindListData.total"
        :page-sizes="[10, 20, 50, 100, 250, 500]"
        :layout="showMobilePage?'total, prev, next,jumper':'total, prev, pager, next, sizes, jumper'"
        style="padding: 0 !important;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
</template>
<script>
import Title from '@/components/Title';
import { getNoticeList, noticeDel, getRiskNoticeList, delRiskNotice, addRiskNotice } from '@/api/config';
import { getLevelList } from '@/api/customer';
import { format } from '@/filters/date';
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import { showModal } from '@/utils/message';

export default {
  components: { Title },
  filters: {
    format,
    typeFilter(type) {
      // 通知类型 0:部门 1:个人
      const arr = ['部门', '个人', '--'];
      return arr[Number(type)] || '--';
    },
    cycleFilter(type) {
      // 通知周期隔开0:不通知1:每天2:每周 3:每月
      const arr = ['不通知', '每天', '每周', '每月'];
      return arr[Number(type)] || '--';
    },
    formatModuleName(val) {
      if (typeof val !== 'number') return '--';
      return {
        0: '客户欠款',
        1: '外采额度',
        2: '项目订单'
      }[val];
    }
  },
  props: {
    type: { // 0-任务通知,1-风险监控通知
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      kindListData: {},
      page: 1,
      perPage: 10,
      listloading: false,
      clientLevel: {}
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  created() {
    this.getCustomeLevelData();
    this.getListData();
  },
  methods: {
    hasRouteAuth,
    getCustomeLevelData() {
      getLevelList().then(res => {
        const result = res && res.data || [];
        this.clientLevel = result.reduce((obj, item) => {
          obj[item.id] = item.name;
          return obj;
        }, {});
      }).catch(e => {
        console.log(e);
      });
    },
    formatCondition(val) {
      const temp = val.map(item => {
        if (item.field === '客户等级') {
          item.valueName = this.clientLevel[item.value];
        } else if (item.value_type === '预计到款金额') {
          item.valueName = '';
        } else if (!item.valueName) {
          item.valueName = item.value;
        }
        return item.field + item.condition + item.value_type + (item.valueName || '');
      }).join(',');
      return temp;
    },
    getListData(reset = false) {
      if (reset) this.page = 1;
      this.listloading = true;
      const getMethod = this.type ? getRiskNoticeList : getNoticeList;
      getMethod({ page: this.page, perPage: this.perPage }).then(res => {
        this.listloading = false;
        if (res.code === 200) {
          res.data.items.forEach(i => {
            i.cycle = Number(i.cycle) || 0;
            // 解析 noticeTime
            i.date = '';
            i.cycleDay = '';
            if (i.noticeTime) {
              const noticeTimeArr = i.noticeTime.split('/');
              i.cycleDay = Number(noticeTimeArr[1]) || 0;
              i.date = noticeTimeArr[2] || '';
            }
            // 转译 通知时间
            i.cycleName = '';
            if (i.date && i.cycle !== 0) i.cycleName = i.date;
            if (i.cycle === 2) {
              i.cycleName = `星期${this.numToString(i.cycleDay)} ${i.cycleName}`;
            } else if (i.cycle === 3) {
              i.cycleName = `${i.cycleDay}号 ${i.cycleName}`;
            }
            if (!this.type) { // 任务通知
              // 转译 通知类型 module
              const arr = ['合同审批', '付款申请', '渠道订单', '项目订单', '每月账号结算'];
              i.moduleName = '';
              if (i.module) {
                i.moduleName = i.module.split(',').map(j => arr[Number(j)]).join(',');
              }
              // 转译 通知对象
              if (i.module === '4' && Array.isArray(i.followUsers)) {
                i.receiveName = i.followUsers.map(item => {
                  return item.username;
                }).join();
              }
            } else {
              if (i.condition && i.condition.length) {
                i.condition.forEach(ele => {
                  if (['欠款额度', '客户欠款金额', '总外采额度', '总可授权外采额度'].includes(ele.value_type)) {
                    ele.value = (ele.value * 100).toFixed(2);
                    ele.valueName = `${ele.value}%`;
                  }
                });
              }
            }
          });
          this.kindListData = res.data;
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.listloading = false;
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getListData(true);
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getListData();
    },
    handleEdit(row) {
      this.$emit('editData', row);
    },
    handleCopy(row) {
      const params = JSON.parse(JSON.stringify(row));
      params.effectUser = params.effectUser.map(item => { return item.id; });
      params.specUser = params.specUser.map(item => { return item.id; });
      if (params.condition && params.condition.length) {
        params.condition.forEach(ele => {
          if (['欠款额度', '客户欠款金额', '总外采额度', '总可授权外采额度'].includes(ele.value_type)) {
            ele.value = ele.value / 100;
          }
        });
      }
      delete params.id;
      addRiskNotice(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.success('复制成功');
          this.getListData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    deleteItem(row) {
      showModal('请确认是否删除').then(() => {
        const params = { id: row.id };
        const delMethod = this.type ? delRiskNotice : noticeDel;
        delMethod(params).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.kindListData.total) {
              this.page--;
            }
            this.getListData();
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    numToString(num) {
      return {
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六',
        7: '日'
      }[num];
    }
  }
};
</script>
<style lang="scss">
.flex {
  display: flex;
  align-items: center;
}
.order-kind-dialog {
  .el-dialog {
    width: 800px !important;
  }
  .el-dialog__body {
    padding: 16px !important;
  }
}
.btn-right {
  position: relative;
  &::before {
    content: '';
    position: absolute;
    right: -9px;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
</style>
